/*
 * Copyright (c) 2015, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.fpx.xms.api.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fpx.open.platform.domain.ae.response.Responses;
import com.fpx.open.platform.service.InvokeLogService;
import com.fpx.xms.api.base.model.InvokeLog;
import com.fpx.xms.api.base.util.CommonUtils;
import com.fpx.xms.api.base.util.JsonUtils;
import com.fpx.xms.api.base.util.SpringContextHolder;

/**
 * 调用日志拦截器
 * @author shiwei
 * @date 2015年6月25日
 */
public class InvokeLogInterceptor extends HandlerInterceptorAdapter {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final String SERVER_ORDER_NO_KEY = InvokeLogInterceptor.class.getName() + ".serverOrderNo";
	public static final String CUSTOMER_ORDER_NO_KEY = InvokeLogInterceptor.class.getName() + ".customerOrderNo";
	public static final String REQUEST_DATE_KEY = InvokeLogInterceptor.class.getName() + ".requestTime";
	public static final String RESPONSE_KEY = InvokeLogInterceptor.class.getName() + ".response";
	public static final String EXCEPTION_KEY = InvokeLogInterceptor.class.getName() + ".ex";
	public static final String INTER_NAME_KEY = InvokeLogInterceptor.class.getName() + ".iterfaceName";
	public static final String INVOKE_LOG_SEQUENCE_KEY = InvokeLogInterceptor.class.getName()+".seq_api_invoke_log";
	public static final String INVOKE_LOG_SEQUENCE = "seq_api_invoke_log";
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Date requestDate = new Date();
		request.setAttribute(REQUEST_DATE_KEY, requestDate);
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		InvokeLog invokeLog = new InvokeLog();
    	try {
    		String serverOrderNo = (String)request.getAttribute(SERVER_ORDER_NO_KEY);
	    	String customerOrderNo = (String)request.getAttribute(CUSTOMER_ORDER_NO_KEY);
	    	Exception exception = (Exception)request.getAttribute(EXCEPTION_KEY);
	    	Date requestTime = (Date)request.getAttribute(REQUEST_DATE_KEY);
	    	Object object = request.getAttribute(RESPONSE_KEY);
	    	String interfaceName = (String)request.getAttribute(INTER_NAME_KEY);
	    	String invokeLogSeq = (String)request.getAttribute(INVOKE_LOG_SEQUENCE_KEY);
    		
	    	invokeLog.setToken(request.getParameter("token"));
	    	invokeLog.setInterfaceName(interfaceName);
	    	invokeLog.setRequestContent(JsonUtils.toJson(request.getParameterMap()));
	    	invokeLog.setRequestTime(requestTime);
	    	String isSuccess = getInvokeResult(ex, invokeLog, object);
	    	invokeLog.setIsSuccess(isSuccess);
	    	if(exception != null){
	    		invokeLog.setException(CommonUtils.getStackTrace(exception));
	    	}
	    	invokeLog.setServerOrderNo(serverOrderNo);
	    	invokeLog.setCustomerOrderNo(customerOrderNo);
	    	String responseContent = JsonUtils.toJson(object);
	    	if(StringUtils.isNotBlank(responseContent) && responseContent.getBytes().length > 2000){
	    		responseContent = responseContent.substring(0, 600);
	    	}
			invokeLog.setResponseContent(responseContent);
			invokeLog.setResponseTime(new Date());
			if(StringUtils.isNotBlank(invokeLogSeq)){
			    invokeLog.setId(Integer.valueOf(invokeLogSeq).intValue());
			}
//			IRabbitmqService rabbitmqService = SpringContextHolder.getBean("rabbitmqService");
//			rabbitmqService.sendData(MessageConstant.XMS_R_AE_ORDER_INVOKE_LOG, invokeLog,invokeLogSeq);
			InvokeLogService invokeLogService = SpringContextHolder.getBean("invokeLogService");
			invokeLogService.addInvokeLog(invokeLog);
    	}catch(Exception e){
    		logger.error("记录调用日志时出错", e);
    	}
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 获取调用结果
	 * @param ex
	 * @param invokeLog
	 * @param object
	 * @return
	 */
	private String getInvokeResult(Exception ex, InvokeLog invokeLog, Object object) {
		String isSuccess = "Y";
		if(ex != null){
			isSuccess = "N";
			invokeLog.setException(CommonUtils.getStackTrace(ex));
		}else{
			if(object != null && object instanceof Responses){
				Responses responses = (Responses) object;
				if(!responses.getResponseItems().getResponse().isSuccess()){
					isSuccess = "N";
				}
			}
		}
		return isSuccess;
	}

}
